﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using ReportWizard.Comparers;
using ReportWizard.DataAccess;
using ReportWizard.Helpers;
using ReportWizard.Properties;

namespace ReportWizard.Forms
{
    public partial class ArchiveForm : IconForm
    {
        private int UserId { get; set; }
        private bool IsArchive { get; set; }
        private int SelectedReportId { get; set; }

        private DateTime MinArchiveDate { get; set; }
        private DateTime MaxArchiveDate { get; set; }

        private List<ArchiveReport> _listReportArchive;
        private List<HistoryRecord> _listHistory;

        public ArchiveForm(Form mdiParent)
        {
            MdiParent = mdiParent;

            InitializeComponent();

            ShowCustomRightButton = false;
            ShowCustomLeftButton = false;
            ShowCheckFooter = false;
        }

        private void CheckAdmin()
        {
            if (Globals.CurrentUser.Admin)
            {
                pAdminOptions.Visible = true;
                List<UserInfo> uList = UserInfo.Select();
                if (uList != null)
                {
                    uList.Insert(0, new UserInfo
                                        {
                                            Id = 0,
                                            Login = Resources.AllUsers
                                        });
                    comboUsers.DataSource = uList;
                }
            }
            else
            {
                UserId = Globals.CurrentUser.Id;
            }
        }

        private DataGridViewTextBoxColumn CreateColumn(string dataPropertyName, string headerText, string name, int width, bool visible, bool styled, bool fill)
        {
            DataGridViewCellStyle cStyle = new DataGridViewCellStyle
                                               {
                                                   Alignment = DataGridViewContentAlignment.MiddleLeft,
                                                   WrapMode = DataGridViewTriState.True
                                               };

            DataGridViewTextBoxColumn column = new DataGridViewTextBoxColumn
                                                   {
                                                       DataPropertyName = dataPropertyName,
                                                       HeaderText = headerText,
                                                       Name = name,
                                                       ReadOnly = true,
                                                       Resizable = DataGridViewTriState.True,
                                                       Visible = visible,
                                                       Width = width
                                                   };
            if (styled)
                column.DefaultCellStyle = cStyle;

            if (fill)
                column.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;

            return column;
        }

        private void CreateGridView()
        {
            dgvArchive.DataSource = null;
            dgvArchive.Columns.Clear();

            if (IsArchive)
            {
                dgvArchive.Columns.AddRange(new DataGridViewColumn[]
                                                {
                                                    CreateColumn("Id", "Id", "dgvcId", 5, false, false, false),
                                                    CreateColumn("Login", "Логин", "dgvcLogin", 120, true, true, false),
                                                    CreateColumn("TemplateName", "Шаблон", "dgvcTemplateName", 305, true, false, false),
                                                    CreateColumn("Name", "Файл", "dgvcName", 305, true, false, false),
                                                    CreateColumn("DateCreated", "Дата", "dgvcDateCreated", 80, true, true, true)
                                                });
            }
            else
            {
                dgvArchive.Columns.AddRange(new DataGridViewColumn[]
                                                {
                                                    CreateColumn("Id", "Id", "dgvcId", 5, false, false, false),
                                                    CreateColumn("Login", "Логин", "dgvcLogin", 120, true, true, false),
                                                    CreateColumn("Action", "Действие", "dgvcEventType", 160, true, false, false),
                                                    CreateColumn("Description", "Описание", "dgvcDescription", 450, true, true, false),
                                                    CreateColumn("DateCreated", "Дата", "dgvcDateCreated", 80, true, true, true)
                                                });
            }
        }

        private void DgvArchiveRowEnter(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvArchive.Rows[e.RowIndex].Cells["dgvcId"].Value != null)
            {
                SelectedReportId = Convert.ToInt32(dgvArchive.Rows[e.RowIndex].Cells["dgvcId"].Value);
            }
        }

        private DateTime GetMinimalDate()
        {
            if (MinArchiveDate.Month != 1)
            {
                if (MinArchiveDate.Day != 1)
                {
                    return new DateTime(MinArchiveDate.Year, MinArchiveDate.Month, MinArchiveDate.Day - 1);
                }
                else
                {
                    return new DateTime(MinArchiveDate.Year, MinArchiveDate.Month - 1, DateTime.DaysInMonth(MinArchiveDate.Year, MinArchiveDate.Month - 1));
                }
            }
            else
            {
                return new DateTime(MinArchiveDate.Year - 1, 12, DateTime.DaysInMonth(MinArchiveDate.Year, 12));
            }
        }

        private void FillOptions()
        {
            CreateGridView();
            if (IsArchive)
            {
                MinArchiveDate = ArchiveReport.SelectDate(UserId, false);
                MaxArchiveDate = ArchiveReport.SelectDate(UserId, true);

                if (MinArchiveDate.Date.Equals(MaxArchiveDate.Date))
                {
                    MinArchiveDate = GetMinimalDate();
                }

                dtpStartDate.Value = dtpStartDate.MinDate = dtpEndDate.MinDate = MinArchiveDate;
                dtpEndDate.Value = dtpStartDate.MaxDate = dtpEndDate.MaxDate = MaxArchiveDate;
                dgvArchive.RowEnter += DgvArchiveRowEnter;
                dgvArchive.DoubleClick += DgvArchiveDoubleClick;
            }
            else
            {
                MinArchiveDate = HistoryRecord.SelectDate(UserId, false);
                MaxArchiveDate = HistoryRecord.SelectDate(UserId, true);

                if (MinArchiveDate.Date.Equals(MaxArchiveDate.Date))
                {
                    MinArchiveDate = GetMinimalDate();
                }

                dtpStartDate.Value = dtpStartDate.MinDate = dtpEndDate.MinDate = MinArchiveDate;
                dtpEndDate.Value = dtpStartDate.MaxDate = dtpEndDate.MaxDate = MaxArchiveDate;
                dgvArchive.RowEnter -= DgvArchiveRowEnter;
                dgvArchive.DoubleClick -= DgvArchiveDoubleClick;
            }
        }

        private void ArchiveFormLoad(object sender, EventArgs e)
        {
            dgvArchive.AutoGenerateColumns = false;
            comboViewType.SelectedIndex = 0;

            CheckAdmin();
        }

        private void CloseForm(object sender, EventArgs e)
        {
            Close();
        }

        private void CheckPeriodCheckedChanged(object sender, EventArgs e)
        {
            dtpStartDate.Enabled = dtpEndDate.Enabled = checkPeriod.Checked;
        }

        private void ComboUsersSelectedIndexChanged(object sender, EventArgs e)
        {
            UserId = Convert.ToInt32(comboUsers.SelectedValue);
            FillOptions();
        }

        private void SelectArchiveClick(object sender, EventArgs e)
        {
            DateTime startArchiveDate = checkPeriod.Checked ? dtpStartDate.Value : MinArchiveDate;
            DateTime endArchiveDate = checkPeriod.Checked ? dtpEndDate.Value : MaxArchiveDate;

            if (IsArchive)
            {
                _listReportArchive = ArchiveReport.Select(UserId, startArchiveDate, endArchiveDate);
                if (_listReportArchive != null)
                {
                    dgvArchive.DataSource = _listReportArchive;
                }
            }
            else
            {
                _listHistory = HistoryRecord.Select(UserId, startArchiveDate, endArchiveDate);
                if (_listHistory != null)
                {
                    dgvArchive.DataSource = _listHistory;
                }
            }
        }

        private void ComboViewTypeSelectedIndexChanged(object sender, EventArgs e)
        {
            IsArchive = (comboViewType.SelectedIndex == 0 || comboViewType.SelectedIndex == 1) &&
                        Convert.ToBoolean(comboViewType.SelectedIndex);
            FillOptions();
        }

        private void DgvArchiveDoubleClick(object sender, EventArgs e)
        {
            Point dgvArchiveAreaPoint = dgvArchive.PointToClient(Cursor.Position);
            DataGridView.HitTestInfo dgvArchiveArea = dgvArchive.HitTest(dgvArchiveAreaPoint.X, dgvArchiveAreaPoint.Y);
            
            if (dgvArchiveArea.Type == DataGridViewHitTestType.Cell && SelectedReportId > 0)
            {
                ArchiveReport ar = ArchiveReport.Select(SelectedReportId);
                if (ar != null)
                {
                    string pathToReport = Path.Combine(Perferences.PathReportFile, ar.Name);
                    if (File.Exists(pathToReport))
                    {
                        Process.Start(pathToReport);
                    }
                    else
                    {
                        ShowMessage.Error(string.Format("Файл отчёта {0} не найден", ar.Name));
                    }
                }
            }
        }

        private void dgvArchive_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            string dataPropertyName = dgvArchive.Columns[e.ColumnIndex].DataPropertyName;
            SortOrder strSortOrder = Digest.GetSortOrder(dgvArchive, e.ColumnIndex);
            dgvArchive.DataSource = null;

            if (IsArchive)
            {
                if (_listReportArchive != null)
                {
                    _listReportArchive.Sort(
                        new ArchiveReportComparer(
                            (ArchiveReport.SortingFields)
                            Enum.Parse(typeof (ArchiveReport.SortingFields), dataPropertyName), strSortOrder));
                    dgvArchive.DataSource = _listReportArchive;
                }
            }
            else
            {
                if (_listHistory != null)
                {
                    _listHistory.Sort(
                        new HistoryRecordComparer(
                            (HistoryRecord.SortingFields)
                            Enum.Parse(typeof (HistoryRecord.SortingFields), dataPropertyName), strSortOrder));
                    dgvArchive.DataSource = _listHistory;
                }
            }

            dgvArchive.Columns[e.ColumnIndex].HeaderCell.SortGlyphDirection = strSortOrder;
        }
    }
}
